const router = require('koa-router')();
const SHA = require('sha1');
const xml2js = require('xml2js');
const wechat = require("../library/wechat.js");
const rp  = require("request-promise");
const config = require('../config/'+process.env.NODE_ENV);
/**
 * 微信验证服务器get请求
 */
router.get('/', async (ctx, next) => {
  let signature = ctx.query.signature ;         //wechat 判断是否服务器正确
  let nonce = ctx.query.nonce;                  //wechat 必须参数三大参数之一
  let timestamp = ctx.query.timestamp;          //wechat 必须参数三大参数之一
  let echostr = ctx.query.echostr;              //wechat 必须参数三大参数之一,只有第一次匹配的时候会有这个参数
  let isWeChat = wechat.isTrueSign(timestamp,nonce,signature);
  console.log(isWeChat);
  if(isWeChat === true)
  {
    ctx.body = echostr;
  }else{
    ctx.body = "微信验证失败";
  }
});

router.post("/",async (ctx,next)=>{
  let signature = ctx.query.signature ;         //wechat 判断是否服务器正确
  let nonce = ctx.query.nonce;                  //wechat 必须参数三大参数之一
  let timestamp = ctx.query.timestamp;          //wechat 必须参数三大参数之一
  // let echostr = ctx.query.echostr;           //wechat 必须参数三大参数之一 
  let isWeChat = wechat.isTrueSign(timestamp,nonce,signature);
  if(isWeChat === true)
  {
    if (ctx.method == 'POST' && ctx.is('text/xml'))
    {
      //接收微信传过来的xml
      let xml = ctx.data.xml;
      let CreateTime = xml.CreateTime[0];//微信发送过来的时间
      let event = xml.Event[0]; //事件类型，subscribe(订阅)、unsubscribe(取消订阅)，已经关注，事件类型，SCAN
      let EventKey = xml.EventKey[0];//未关注过，事件KEY值，qrscene_为前缀，后面为二维码的参数值。关注过，事件KEY值，是一个32位无符号整数，即创建二维码时的二维码scene_id
      let FromUserName = xml.FromUserName[0];
      let ToUserName = xml.ToUserName[0];//收到账号
      console.log("event:%s,EventKey:%s",event,EventKey);
      if( event == "subscribe" || event == "SCAN" )//表示用户关注或者扫码进入的
      {
          //用户的userId
          let firstOne = EventKey.indexOf("qrscene_");
          let userId;
          if(firstOne != -1)//表示第一次登录
          {
            userId = EventKey.substring(8);
          }else{
            userId = EventKey;
          }
          let MsgType = xml.MsgType[0];//消息类型，event
          let Ticket = xml.Ticket[0];//二维码的ticket，可用来换取二维码图片
          let xmlStr = wechat.getXmlContentBySubscribe(FromUserName,ToUserName,userId);
          ctx.response.type = 'application/xml';
          ctx.response.body = xmlStr;
          return;
      }else if(event == "CLICK" && EventKey == "V1001_service"){//表示点击客服过来的
          let xmlStr = wechat.getXmlContentByClick(FromUserName,ToUserName);
          ctx.response.type = 'application/xml';
          ctx.response.body = xmlStr;
          return;
      }
    }else{
         ctx.body = true;
         return;
    }
  }else{
    ctx.body = "微信验证失败";
  }
});
/**
 * 设置自定义菜单
 */
router.post("/setCustomMenu",async (ctx,next)=>{
    let access_token = await wechat.getToken();
    let menuJson = wechat.getCustomMenu();
    let uri  = "https://api.weixin.qq.com/cgi-bin/menu/create?access_token="+access_token;
    let options = {
      method: 'POST',
      uri: uri,
      body: menuJson,
      json: true 
    };
    let result = "";
    await rp(options).then(function (body) {
                result = body;
        })
        .catch(function (err) {
            result = err;
        });
    if(result.errcode == 0)
    {
      ctx.body = "菜单设置成功";
    }else{
      ctx.body = "菜单设置失败，errcode:"+result.errcode;
    }
});

/**
 * 给指定用户推送短信，还款
 * @param {*String M} userName 用户姓名
 * @param {*String M} productName 标的名称
 * @param {*Int M} money 金额
 * @param {*String M} repaymentTime 还款时间
 * @param {*Int M} productPeriod 投资天数
 * @param {*String M} openId 微信ID
 */
router.post("/repaymentSend",async function(ctx,next){
    //获取提交过来的参数
    let userName = ctx.request.body.userName;//用户姓名
    let productName = ctx.request.body.productName;//标的名称
    let money = ctx.request.body.money;//金额
    let repaymentTime = ctx.request.body.repaymentTime;//还款时间
    let productPeriod = ctx.request.body.productPeriod;//标的周期
    let openId = ctx.request.body.openId;//微信ID
    let wxDomain = config.wxDomain;
    let access_token = await wechat.getToken();
    money = wechat.toDecimal2(money/100);
    let first = `尊敬的${userName.substring(0,1)}先生/女、女士：`;
    let uri  = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;
    let options = {
      method: 'POST',
      uri: uri,
      body:{
            "touser":openId,
            "template_id":"dQ242zP5TXRIq2m2MRTtbIHCsjjn0BALhJONmkY9xw0",
            "url":"http://wx.lingqd.com/login",
            "topcolor":"#253159",
            "data":{
                "first":{
                  "value":first,
                  "color":"#253159"
                },
                "keyword1":{
                  "value":productName,
                  "color":"#253159"
                },
                "keyword2":{
                  "value":money,
                  "color":"#253159"
                },
                "keyword3":{
                  "value":repaymentTime,
                  "color":"#253159"
                },
                "keyword4":{
                  "value":"到期还本付息",
                  "color":"#253159"
                },
                "keyword5":{
                  "value":productPeriod,
                  "color":"#253159"
                },
                "remark":{
                  "value":"感谢您对零钱袋的支持！",
                  "color":"#253159"
                }
            }
        },
      json: true 
    };
    let result = "";
    await rp(options).then(function (body) {
                result = body;
        })
        .catch(function (err) {
            result = err;
        });
    // 设置response的Content-Type:
    ctx.response.type = 'application/json';
    // 设置response的内容:
    ctx.response.body = {"status":"success","msg":"还款提醒","result":result};
    return;
});
/**
 * 给指定用户发送满标提醒
 */
router.post("/remindSend",async function(ctx,next){
    //获取提交过来的参数
    let productName = ctx.request.body.productName;//标的名称
    let productId = ctx.request.body.productId;//流水号
    let openId = ctx.request.body.openId;//提现反馈状态
    let raisingFund = ctx.request.body.raisingFund;//募集金额
    let productPeriod = ctx.request.body.productPeriod;//投资期限
    let updateTime = ctx.request.body.updateTime;//满标时间
    let access_token = await wechat.getToken();
    let adminDomain = config.adminDomain;
    raisingFund = wechat.toDecimal2(raisingFund/100);
    let uri  = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;
    let first = `标名为【${productName}】,标的ID为【${productId}】已经满标`;
    let options = {
      method: 'POST',
      uri: uri,
      body:{
            "touser":openId,
            "template_id":"fNhVOKdp5-mk8Lhewh5qJUIb0Orc1QZaOeQlk_yey_w",
            "url":adminDomain,
            "topcolor":"#253159",
            "data":{
                "first":{
                  "value":first,
                  "color":"#253159"
                },
                "keyword1":{//投资总额
                  "value":raisingFund,
                  "color":"#253159"
                },
                "keyword2":{//投资期限
                  "value":productPeriod,
                  "color":"#253159"
                },
                "keyword3":{//还款方式
                  "value":"到期还本付息",
                  "color":"#253159"
                },
                "keyword4":{//满标时间
                  "value":updateTime,
                  "color":"#253159"
                },
                "remark":{
                  "value":"请尽快处理！",
                  "color":"#253159"
                }
            }
        },
      json: true 
    };
    let result = "";
    await rp(options).then(function (body) {
                result = body;
        })
        .catch(function (err) {
            result = err;
        });
    // 设置response的Content-Type:
    ctx.response.type = 'application/json';
    // 设置response的内容:
    ctx.response.body = {"status":"success","msg":"满标提醒","result":result};
    return;
});
/**
 * 给指定用户发送募集期到未满标提醒
 */
router.post("/remindSendByRaise",async function(ctx,next){
    //获取提交过来的参数
    let productName = ctx.request.body.productName;//标的名称
    let productId = ctx.request.body.productId;//流水号
    let openId = ctx.request.body.openId;//提现反馈状态
    let adminDomain = config.adminDomain;
    let access_token = await wechat.getToken();
    let uri  = "https://api.weixin.qq.com/cgi-bin/message/template/send?access_token="+access_token;
    let options = {
      method: 'POST',
      uri: uri,
      body:{
            "touser":openId,
            "template_id":"y5aSK9RM4g46dX50q0tWwmEJzQEExIU0bvSDTZ0YHLY",
            "url":adminDomain,
            "topcolor":"#253159",
            "data":{
                "productName":{
                  "value":productName,
                  "color":"#253159"
                },
                "productId":{
                  "value":"募集期时间到，未满标",
                  "color":"#253159"
                }
            }
        },
      json: true 
    };
    let result = "";
    await rp(options).then(function (body) {
                result = body;
        })
        .catch(function (err) {
            result = err;
        });
    // 设置response的Content-Type:
    ctx.response.type = 'application/json';
    // 设置response的内容:
    ctx.response.body = {"status":"success","msg":"募集期到未满标提醒","result":result};
    return;
});
/**
 * 获取access_token
 */
router.post('/getAccessToken',async (ctx,next)=>{
  let access_token = await wechat.getToken();
   // 设置response的Content-Type:
  ctx.response.type = 'application/json';
  // 设置response的内容:
  ctx.response.body = {"status":"success","msg":"获取token成功","AccessToken":access_token};
  return;
});



//测试
router.get('/string', async (ctx, next) => {
  ctx.body = 'koa2 string'
  if (ctx.method == 'POST' && ctx.is('text/xml')) {
      xml = ()=> {
                return new Promise((resolve, reject)=> {
                    let buf = '';
                    ctx.req.setEncoding('utf8');
                    ctx.req.on('data', chunk=> {
                        buf += chunk;
                    });

                    ctx.req.on('end', ()=> {
                        resolve(buf);
                    });
                })
            };
                // ctx.req.setEncoding('utf8')
                // await ctx.req.on('data', (chunk) => {
                //     xml =  chunk;
                // })      
  } 
})


router.get('/json', async (ctx, next) => {
  ctx.body = {
    title: 'koa2 json'
  }
})

module.exports = router
